#include "sem.h"

#include "thread.h"
#include "mem.h"

#include <stdio.h>
#include <assert.h>

static int val;

static int
func1(void *arg)
{
    printf("step 1: func1 %d\n", val);
    assert(val == 0);
    val = 100;
    Thread_pause();

    printf("step 3: func1 %d\n", val);
    assert(val == 200);
    val = 300;

    Sem_T *s = *(Sem_T**)arg;
    Sem_wait(s);

    printf("step 5: func1 %d\n", val);
    assert(val == 400);
    return 0;
}

static int 
func2(void *arg)
{
    printf("step 2: func2 %d\n", val);
    assert(val == 100);
    val = 200;
    Thread_pause();

    printf("step 4: func2 %d\n", val);
    assert(val == 300);
    val = 400;

    Sem_T *s = *(Sem_T**)arg;
    Sem_signal(s);
    return 0;
}

static void
test()
{
    Sem_T *s = Sem_new(0);
    Thread_new(func1, &s, (int)sizeof(s));
    Thread_new(func2, &s, (int)sizeof(s));
    Thread_join(NULL);
    FREE(s);
}

int main()
{
    Thread_init(0);
    test();
    printf("main exit now!\n");
    Thread_exit(0);
    return 0;
}

